package com.whisperly.echotalk.starryb.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.hjq.toast.Toaster;
import com.whisperly.echotalk.bean.VersionCheckResponse;
import com.whisperly.echotalk.bllmodel.UpdateInfo;

public class UpdateNotificationHelper {
    private static final String TAG = "UpdateNotification";
    private static final String PREF_NAME = "update_preferences";
    private static final String KEY_DISMISSED_VERSION = "dismissed_version";
    private static final String KEY_REMIND_LATER_TIME = "remind_later_time";
    private static final long REMIND_INTERVAL = 7 * 24 * 60 * 60 * 1000; // 7天后再提醒
    
    private Context context;
    
    public UpdateNotificationHelper(Context context) {
        this.context = context;
    }
    
    /**
     * 显示温和的更新提示
     */
    public void showUpdateNotification(VersionCheckResponse response) {
        if (!response.getHasUpdate() || !response.getShowNotification()) {
            return;
        }
        
        // 检查用户是否已经忽略了这个版本
        if (isVersionDismissed(response.getVersionCode())) {
            Log.d(TAG, "用户已忽略版本: " + response.getLatestVersion());
            return;
        }
        
        // 检查是否在"稍后提醒"的时间间隔内
        if (isInRemindLaterInterval()) {
            Log.d(TAG, "在稍后提醒的时间间隔内，跳过提示");
            return;
        }

        // 根据更新类型选择提示方式
        switch (response.getUpdateType()) {
            case "RECOMMENDED":
                showRecommendedUpdateDialog(response);
                break;
            case "OPTIONAL":
                showOptionalUpdateSnackbar(response);
                break;
            case "NOTIFY_ONLY":
                // 仅记录日志，不显示UI
                Log.i(TAG, "发现新版本但仅记录: " + response.getLatestVersion());
                break;
            default:
                showSimpleUpdateDialog(response);
                break;
        }
    }
    
    /**
     * 显示推荐更新对话框
     */
    private void showRecommendedUpdateDialog(VersionCheckResponse response) {
        new AlertDialog.Builder(context)
            .setTitle("发现新版本 " + response.getLatestVersion())
            .setMessage(buildUpdateMessage(response))
            .setNegativeButton("稍后提醒", (dialog, which) -> {
                setRemindLaterTime();
                Toaster.show("7天后再次提醒");
            })
            .setNeutralButton("忽略此版本", (dialog, which) -> {
                dismissVersion(response.getVersionCode());
                Toaster.show("已忽略此版本");
            })
            .setCancelable(true)
            .show();
    }
    
    /**
     * 显示可选更新Snackbar
     */
    private void showOptionalUpdateSnackbar(VersionCheckResponse response) {
        // 这里需要一个View来显示Snackbar，通常在Activity中调用
        Toaster.show("发现新版本 " + response.getLatestVersion() + "，点击设置查看详情");
    }
    
    /**
     * 显示简单更新对话框
     */
    private void showSimpleUpdateDialog(VersionCheckResponse response) {
        new AlertDialog.Builder(context)
            .setTitle("版本更新")
            .setMessage("发现新版本 " + response.getLatestVersion() + "\n\n" + response.getDescription())
            .setPositiveButton("查看详情", (dialog, which) -> {
                Intent intent = new Intent(context, UpdateInfo.class);
                context.startActivity(intent);
            })
            .setNegativeButton("稍后", null)
            .show();
    }
    
    /**
     * 构建更新消息
     */
    private String buildUpdateMessage(VersionCheckResponse response) {
        StringBuilder message = new StringBuilder();
        
        if (response.getDescription() != null) {
            message.append(response.getDescription()).append("\n\n");
        }
        
        if (response.getUpdateContent() != null) {
            message.append("更新内容:\n").append(response.getUpdateContent()).append("\n\n");
        }
        
        return message.toString().trim();
    }
    
    /**
     * 检查版本是否已被忽略
     */
    private boolean isVersionDismissed(int versionCode) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        int dismissedVersion = prefs.getInt(KEY_DISMISSED_VERSION, -1);
        return dismissedVersion == versionCode;
    }
    
    /**
     * 忽略版本
     */
    private void dismissVersion(int versionCode) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putInt(KEY_DISMISSED_VERSION, versionCode).apply();
    }
    
    /**
     * 设置稍后提醒时间
     */
    private void setRemindLaterTime() {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putLong(KEY_REMIND_LATER_TIME, System.currentTimeMillis()).apply();
    }
    
    /**
     * 检查是否在稍后提醒的时间间隔内
     */
    private boolean isInRemindLaterInterval() {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        long remindLaterTime = prefs.getLong(KEY_REMIND_LATER_TIME, 0);
        
        if (remindLaterTime == 0) {
            return false; // 从未设置过稍后提醒
        }
        
        return (System.currentTimeMillis() - remindLaterTime) < REMIND_INTERVAL;
    }
    
    /**
     * 清除所有忽略和稍后提醒的设置
     */
    public void clearAllSettings() {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().clear().apply();
    }
}